<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="handleBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <view class="nav-title">个人资料</view>
      <view class="nav-right">
        <text :class="['save-btn', hasChanged ? 'active' : '']" @click="handleSave">保存</text>
      </view>
    </view>

    <!-- 微信原生加载状态 -->
    <view v-if="loading" class="loading-mask">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view v-else class="content" scroll-y>
      <!-- 基础信息区块 -->
      <view class="section">
        <view class="section-title">基础信息</view>
        <view class="info-item">
          <text class="item-label">头像</text>
          <view class="item-content avatar-content">
            <image 
              class="avatar"
              :src="formData.avatar || 'https://picsum.photos/100/100?random=1'"
              @click="handleChangeAvatar" 
              @error="handleImageError"
            ></image>
            <text class="change-avatar-text" @click="handleChangeAvatar">修改头像</text>
          </view>
        </view>
        <view class="info-item">
          <text class="item-label">用户ID</text>
          <text class="item-content readonly">{{ formData.userId }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">姓名</text>
          <text class="item-content readonly">{{ formData.name }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">学院</text>
          <text class="item-content readonly">{{ formData.academy }}</text>
        </view>
      </view>

      <!-- 可编辑信息区块 -->
      <view class="section">
        <view class="section-title">联系方式</view>
        <view class="info-item">
          <text class="item-label">手机号</text>
          <input 
            class="item-content input" 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            :class="{'input-error': formErrors.phone}"
          />
          <text v-if="formErrors.phone" class="error-message">{{ formErrors.phone }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">邮箱</text>
          <input 
            class="item-content input email-input" 
            v-model="formData.email" 
            placeholder="请输入邮箱"
            :class="{'input-error': formErrors.email}"
          />
          <text v-if="formErrors.email" class="error-message">{{ formErrors.email }}</text>
        </view>
        <view class="info-item" @click="handleChangePassword">
          <text class="item-label">密码</text>
          <view class="item-content">
            <text class="password-text">修改密码</text>
            <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 账号信息区块 -->
      <view class="section">
        <view class="section-title">账号信息</view>
        <view class="info-item">
          <text class="item-label">用户角色</text>
          <text class="item-content readonly">{{ roleMap[formData.role] || formData.role }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">注册时间</text>
          <text class="item-content readonly">{{ formData.createTime || '未设置' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">最后更新</text>
          <text class="item-content readonly">{{ formData.updateTime || '未更新' }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, watch } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';

  // 角色映射
  const roleMap: Record<number, string> = {
    0: '普通用户',
    1: '管理员',
    2: '超级管理员'
  };

  // 表单数据类型定义
  type UserFormData = {
    userId: string;
    name: string;
    academy: string;
    phone: string;
    email: string;
    avatar: string;
    role: number;
    createTime: string | Date;
    updateTime: string | Date;
  };

  // 表单数据
  const formData = reactive<UserFormData>({
    userId: '',
    name: '',
    academy: '',
    phone: '',
    email: '',
    avatar: '',
    role: 0,
    createTime: '',
    updateTime: ''
  });

  // 原始数据（仅存储可编辑字段的副本）
  const originalData = ref<UserFormData>({...formData});

  // 加载状态
  const loading = ref(true);

  // 表单错误信息
  const formErrors = reactive({
    phone: '',
    email: ''
  });

  // 是否有修改（仅比较可编辑字段，不包括头像）
  const hasChanged = computed(() => {
    return formData.phone !== originalData.value.phone || 
           formData.email !== originalData.value.email;
  });

  // 验证手机号
  const validatePhone = (phone: string): string => {
    if (!phone) return '手机号不能为空';
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) return '请输入有效的手机号';
    return '';
  };

  // 验证邮箱
  const validateEmail = (email: string): string => {
    if (!email) return '邮箱不能为空';
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(email)) return '请输入有效的邮箱地址';
    return '';
  };

  // 验证所有表单字段
  const validateForm = (): boolean => {
    let isValid = true;
    
    const phoneError = validatePhone(formData.phone);
    if (phoneError) {
      formErrors.phone = phoneError;
      isValid = false;
    } else {
      formErrors.phone = '';
    }
    
    const emailError = validateEmail(formData.email);
    if (emailError) {
      formErrors.email = emailError;
      isValid = false;
    } else {
      formErrors.email = '';
    }
    
    return isValid;
  };

  // 获取用户信息
  const fetchUserInfo = async (userId: string) => {
    try {
      loading.value = true;
      uni.showLoading({ title: '加载中' });
      
      const res = await uni.request({
        url: 'http://172.20.10.2:8080/api/user/get',
        method: 'GET',
        header: { 'content-type': 'application/json' },
        data: { userId }
      });
      
      if (res.statusCode >= 200 && res.statusCode < 300) {
        const userData = res.data;
        if (userData && userData.data) {
          // 直接赋值后端数据
          Object.assign(formData, userData.data);
          
          // 仅复制可编辑字段到原始数据
          originalData.value = { 
            ...originalData.value,
            phone: formData.phone,
            email: formData.email,
            avatar: formData.avatar
          };
        } else {
          uni.showToast({ title: '获取用户信息失败', icon: 'none' });
        }
      } else {
        uni.showToast({ title: '服务器错误', icon: 'none' });
      }
    } catch (error) {
      console.error('获取用户信息出错:', error);
      uni.showToast({ title: '网络请求出错', icon: 'none' });
    } finally {
      uni.hideLoading();
      loading.value = false;
    }
  };

  // 初始化数据
  onLoad(() => {
    const userId = uni.getStorageSync('userId');
    if (userId) {
      fetchUserInfo(userId);
    } else {
      uni.showToast({ title: '用户ID不存在', icon: 'none' });
    }
  });

  // 返回
  const handleBack = () => {
    if (hasChanged.value) {
      uni.showModal({
        title: '提示',
        content: '您有未保存的修改，确定要返回吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack({ delta: 1 });
          }
        }
      });
    } else {
      uni.navigateBack({ delta: 1 });
    }
  };

  // 保存
  const handleSave = async () => {
    if (!hasChanged.value) return;
    
    if (validateForm()) {
      await saveUserInfo();
    } else {
      // 表单验证失败，显示第一个错误
      const firstError = Object.values(formErrors).find(error => error);
      if (firstError) {
        uni.showToast({
          title: firstError,
          icon: 'none',
          duration: 2000
        });
      }
    }
  };

  // 保存用户信息
  const saveUserInfo = async () => {
    try {
      uni.showLoading({ title: '保存中' });
      const res = await uni.request({
        url: `http://172.20.10.2:8080/api/user/${formData.userId}`,
        method: 'PUT',
        header: { 'content-type': 'application/json' },
        data: { 
          phone: formData.phone, 
          email: formData.email
        }
      });

      if (res.statusCode === 200) {
        formData.updateTime = new Date();
        originalData.value = { 
          ...originalData.value,
          phone: formData.phone,
          email: formData.email
        };
        
        // 保存成功后显示微信原生弹窗
        uni.showModal({
          title: '提示',
          content: '个人资料更新成功！',
          showCancel: false,
          confirmText: '确定',
          success: (res) => {
            if (res.confirm) {
              // 可以在这里添加关闭页面或其他操作
            }
          }
        });
      } else {
        uni.showToast({ title: '保存失败，请稍后重试', icon: 'none' });
      }
    } catch (error) {
      console.error('保存出错:', error);
      uni.showToast({ title: '网络请求出错', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  };

  // 修改头像
  const handleChangeAvatar = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'],
      success: (res) => {
        uploadAvatar(res.tempFilePaths[0]);
      },
      fail: (err) => {
        console.error('选择图片失败', err);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  };
  
  // 上传状态控制
  const isUploading = ref(false);
  const uploadProgress = ref(0);
  
  // 上传头像（独立操作，不关联保存按钮）
  const uploadAvatar = (filePath) => {
    // 防止并发上传
    if (isUploading.value) return;
    
    isUploading.value = true;
    uploadProgress.value = 0;
    
    uni.showLoading({ title: '上传中' });
    
    // 获取文件名和扩展名
    const fileName = filePath.split('/').pop();
    const fileExt = fileName ? fileName.split('.').pop() : 'jpg';
    
    // 上传任务
    const uploadTask = uni.uploadFile({
      url: 'http://172.20.10.2:8080/api/user/upload/avatar',
      filePath,
      name: 'file',
      formData: { 
        userId: formData.userId,
        fileExt: fileExt
      },
      success: (res) => {
        // 处理上传成功响应
        try {
          // 解析后端返回的JSON数据
          const responseData = JSON.parse(res.data);
          
          // 检查状态码
          if (responseData.code === 200) {
            // 成功获取URL
            if (responseData.data && responseData.data.url) {
              formData.avatar = responseData.data.url;
              originalData.value.avatar = responseData.data.url;
              
              uni.showToast({ 
                title: '头像更新成功', 
                icon: 'success',
                duration: 2000
              });
            } else {
              throw new Error('未获取到图片URL');
            }
          } else {
            // 后端返回错误
            throw new Error(responseData.message || '头像上传失败');
          }
        } catch (parseError) {
          console.error('解析响应失败', parseError);
          uni.showToast({ 
            title: '服务器响应格式错误', 
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        // 处理上传失败
        console.error('上传头像失败', err);
        uni.showToast({ 
          title: '网络请求出错', 
          icon: 'none',
          duration: 2000
        });
      },
      complete: () => {
        // 完成后的操作
        uni.hideLoading();
        isUploading.value = false;
        uploadProgress.value = 0;
      }
    });
    
    // 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      uploadProgress.value = res.progress;
      console.log('上传进度', res.progress);
      console.log('已经上传的数据长度', res.totalBytesSent);
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
    });
  };

  // 修改密码
  const handleChangePassword = () => {
    const pages = getCurrentPages();
    const nextPage = '/pages/change-password/change-password';
    uni.navigateTo({ url: nextPage });
  };

  // 格式化日期
  const formatDate = (date: string | Date) => {
    if (!date) return '未设置';
    try {
      const d = new Date(date);
      return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`;
    } catch {
      return date.toString();
    }
  };

  // 监听表单变化，实时验证
  watch(() => formData.phone, (newVal) => {
    formErrors.phone = validatePhone(newVal);
  });

  watch(() => formData.email, (newVal) => {
    formErrors.email = validateEmail(newVal);
  });
</script>

<style>
page {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.nav-left,
.nav-right {
  width: 100rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.save-btn {
  font-size: 16px;
  color: #999;
  text-align: right;
}

.save-btn.active {
  color: #007aff;
}

.content {
  flex: 1;
  overflow: auto;
  padding-bottom: 20rpx;
}

.section {
  margin: 20rpx 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.section-title {
  padding: 24rpx 30rpx;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
}

.info-item {
  display: flex;
  align-items: center;
  min-height: 110rpx;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
  box-sizing: border-box;
  justify-content: space-between;
}

.info-item:last-child {
  border-bottom: none;
}

.item-label {
  width: auto;
  min-width: 100rpx; /* 设置最小宽度，确保标签有足够空间 */
  font-size: 16px;
  color: #333;
  margin-right: 20rpx; /* 增加标签和内容之间的间距 */
}

.item-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 16px;
  color: #666;
  position: relative; /* 为错误信息定位提供参考 */
  padding-right: 0; /* 移除右侧内边距 */
}

.avatar-content {
  flex-direction: column;
  align-items: flex-end;
  padding: 10rpx 0;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #eee;
  margin-bottom: 10rpx;
}

.change-avatar-text {
  color: #007aff;
  font-size: 14px;
}

.item-content.readonly {
  color: #666;
  overflow: visible; /* 允许内容溢出容器 */
  white-space: nowrap;
  text-align: right; /* 文本右对齐 */
}

/* 输入框容器样式 */
.input-container {
  width: 100%;
  position: relative;
}

.input {
  height: 110rpx;
  text-align: right;
  color: #333;
  width: 100%;
  padding-right: 0;
  box-sizing: border-box;
  white-space: nowrap; /* 输入内容不换行 */
  overflow: visible; /* 允许内容溢出 */
  position: relative;
  z-index: 1; /* 确保输入框内容显示在错误信息上方 */
}

.email-input {
  font-size: 14px;
  padding-right: 0;
}

.input-error {
  color: #ff3b30 !important;
}

/* 错误信息样式 */
.error-message {
  position: absolute;
  bottom: -25rpx; /* 调整位置，避免遮挡输入内容 */
  right: 0;
  color: #ff3b30;
  font-size: 12px;
  z-index: 2;
  white-space: nowrap; /* 错误信息不换行 */
}

/* 密码修改项样式 */
.password-item {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
}

.password-text {
  margin-right: 10rpx;
  color: #666;
  text-align: right;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 100;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
